import upng from '../../../utils/upng';
import util from '../../../utils/util';
import * as API from '../../../api/myApi';

let SCREEN_RATIO = 1.2;
let SCREEN_WIDTH = 750;
let SCREEN_HEIGHT = 750 * SCREEN_RATIO;
let PAGE_X, // 手按下的x位置
  PAGE_Y, // 手按下y的位置
  // PR = wx.getSystemInfoSync().pixelRatio, // dpi
  T_PAGE_X, // 手移动的时候x的位置
  T_PAGE_Y, // 手移动的时候Y的位置
  CUT_W,  // 初始化拖拽元素的宽度
  CUT_H,  //  初始化拖拽元素的高度
  DRAG_DATA,
  IMG_RATIO,  // 图片比例
  IMG_REAL_W,  // 图片实际的宽度
  IMG_REAL_H,   // 图片实际的高度
  QUALITY_WIDTH = 500; // 设置生成的图片宽度

Page({
  /**
   * 页面的初始数据
   */
  data: {
    imageSrc: '',
    returnImage: '',
    isShowImg: false,
    isGenerateImg: false,
    // 初始化的宽高
    cropperInitW: SCREEN_WIDTH,
    cropperInitH: SCREEN_HEIGHT,
    // 动态的宽高
    cropperW: SCREEN_WIDTH,
    cropperH: SCREEN_WIDTH,
    // 动态的left top值
    cropperL: 0,
    cropperT: 0,

    transL: 0,
    transT: 0,

    imageW: 0,
    imageH: 0,

    // 裁剪框 宽高
    cutW: 0,
    cutH: 0,
    cutL: 0,
    cutT: 0,
    qualityWidth: QUALITY_WIDTH
  },

  // 拖动时候触发的touchStart事件
  contentStartMove(e) {
    PAGE_X = e.touches[0].pageX;
    PAGE_Y = e.touches[0].pageY;
  },
  // 拖动时候触发的touchMove事件
  contentMoveing(e) {
    var dragLengthX = (PAGE_X - e.touches[0].pageX);
    var dragLengthY = (PAGE_Y - e.touches[0].pageY);

    var _data = this.data;
    var left = _data.cutL - dragLengthX;
    var top = _data.cutT - dragLengthY;
    if (left < 0) left = 0;
    if (left + _data.cutW > _data.cropperW) left = _data.cropperW - _data.cutW;
    if (top < 0) top = 0;
    if (top + _data.cutH > _data.cropperH) top = _data.cropperH - _data.cutH;
    this.setData({
      cutL: left,
      cutT: top
    });

    PAGE_X = e.touches[0].pageX;
    PAGE_Y = e.touches[0].pageY;
  },
  contentTouchEnd() {
  },

  // 设置大小的时候触发的touchStart事件
  dragStart(e) {
    T_PAGE_X = e.touches[0].pageX;
    T_PAGE_Y = e.touches[0].pageY;
    CUT_W = this.data.cutW;
    CUT_H = this.data.cutH;
  },

  // 设置大小的时候触发的touchMove事件
  dragMove(e) {
    var _data = this.data;
    var dragLengthX = (e.touches[0].pageX - T_PAGE_X);
    var dragLengthY = (e.touches[0].pageY - T_PAGE_Y);
    var cut_w = CUT_W + dragLengthX;
    var cut_h = CUT_H + dragLengthY;
    if (cut_w < 0) cut_w = 0;
    if (cut_h < 0) cut_h = 0;
    if (_data.cutL + cut_w > _data.cropperW) cut_w = _data.cropperW - _data.cutL;
    if (_data.cutT + cut_h > _data.cropperH) cut_h = _data.cropperH - _data.cutT;
    if (cut_h < cut_w) cut_w = cut_h;
    if (cut_h > cut_w) cut_h = cut_w;
    this.setData({
      cutW: cut_w,
      cutH: cut_h,
    });
  },
  dragEnd() { },
  // getImage: function () {
  //   var _this = this;
  //   wx.chooseImage({
  //     success: function (res) {
  //       _this.setData({
  //         imageSrc: res.tempFilePaths[0],
  //       })
  //       _this.loadImage();
  //     },
  //   });
  // },

  loadImage(src) {
    var _this = this;
    wx.showLoading({
      title: '图片加载中...',
    });

    wx.getImageInfo({
      src: src || _this.data.imageSrc,
      success: function success(res) {
        IMG_REAL_W = res.width;
        IMG_REAL_H = res.height;
        IMG_RATIO = IMG_REAL_W / IMG_REAL_H;

        // 若图片为横向
        if (IMG_RATIO >= 1) {
          var data = {
            isShowImg: true,
            cropperW: SCREEN_WIDTH,
            cropperH: SCREEN_WIDTH / IMG_RATIO,
            // 初始化left right
            cropperL: 0,
            cropperT: Math.ceil((SCREEN_HEIGHT - SCREEN_WIDTH / IMG_RATIO) / 2),
            // 裁剪框  宽高
            cutW: Math.ceil(SCREEN_WIDTH / IMG_RATIO),
            cutH: Math.ceil(SCREEN_WIDTH / IMG_RATIO),
            cutL: 0,
            cutT: 0
          };
          _this.setData(data);
        } else {
          // 若图片为纵向
          var data = {
            isShowImg: true,
            cropperW: SCREEN_WIDTH * IMG_RATIO,
            cropperH: SCREEN_WIDTH,
            // 初始化left right
            cropperL: Math.ceil((SCREEN_WIDTH - SCREEN_WIDTH * IMG_RATIO) / 2),
            cropperT: (SCREEN_HEIGHT - SCREEN_WIDTH) / 2,
            // 裁剪框的宽高
            cutW: SCREEN_WIDTH * IMG_RATIO,
            cutH: SCREEN_WIDTH * IMG_RATIO,
            cutL: 0,
            cutT: 0
          };
          _this.setData(data);
        }
        wx.hideLoading()
      }
    });
  },

  // 获取图片
  getImageInfo() {
    let _this = this;
    wx.showLoading({
      title: '正在上传...',
    });
    this.setData({ isGenerateImg: true });

    var _data = this.data;
    var sx = _data.cutL * IMG_REAL_W / _data.cropperW; // 开始剪切的 x 坐标位置。
    var sy = _data.cutT * IMG_REAL_H / _data.cropperH; // 开始剪切的 y 坐标位置。
    var swidth = _data.cutW * IMG_REAL_W / _data.cropperW; // 被剪切图像的宽度。
    var sheight = _data.cutH * IMG_REAL_H / _data.cropperH; // 被剪切图像的高度。
    var x = 0; // 在画布上放置图像的 x 坐标位置。
    var y = 0; // 在画布上放置图像的 y 坐标位置。
    var width = QUALITY_WIDTH; // 要使用的图像的宽度。（伸展或缩小图像）
    var height = QUALITY_WIDTH; // 要使用的图像的高度。（伸展或缩小图像）

    // 将图片写入画布
    const ctx = wx.createCanvasContext('myCanvas');
    ctx.drawImage(_data.imageSrc, sx, sy, swidth, sheight, x, y, width, height);
    ctx.draw(true, () => {
      // 2. 获取图像数据， API 1.9.0
      wx.canvasGetImageData({
        canvasId: 'myCanvas',
        x: 0,
        y: 0,
        width: width,
        height: height,
        success(res) {
          // 3. IOS图像反转
          let buffer = res.data.buffer;
          try {
            let systemInfo = wx.getSystemInfoSync();
            let platform = systemInfo.platform;
            if (platform === 'ios') {
              buffer = util.revertImage(res.data, res.width, res.height);
            }
          } catch (e) {
          }
          // 4. png图形
          let pngData = upng.encode([buffer], res.width, res.height)
          // 5. base64编码
          let base64 = wx.arrayBufferToBase64(pngData);
          _this.uploadBase64img(base64);
        }
      })
    });
  },

  revertImageData(buffer, width, height) {
    if (!buffer) return buffer;
    let dataViews = [];
    let len = width * 4;
    for (let i = 0; i < height; i++) {
      let start = i * width * 4;
      let newBuff = buffer.slice(start, start + len);
      dataViews.unshift(newBuff);
    }
    return util.concatArrayBuffer(Uint8Array, ...dataViews);
  },

  cancel() {
    util.preventMoreClick(this, () => {
      wx.navigateBack({
        delta: 1
      })
    })
  },

  uploadBase64img(url) {
    API.uploadImg({
      imgStr: url
    }).then(data => {
      wx.hideLoading();
      this.setData({ isGenerateImg: false });
      API.editUserInfo({ photo: data.url }).then(result => {
        util.toast('上传成功');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          })
        }, 500)
      }, err => {
        util.toast(err);
      })
    }, err => {
      util.toast('上传失败');
    });
  },

  onLoad: function (options) {
    this.setData({
      imageSrc: options.url
    });
    this.loadImage(options.url);
  },
  onReady: function () {
  },
  onShow: function () {
  },
  onPullDownRefresh: function () {
  },
  onReachBottom: function () {
  }
})